//
//  CYShareManager.m
//  cyjf
//
//  Created by tauCross on 2017/7/31.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYShareManager.h"

#import "CYGlobal.h"

#import <WXApi.h>
#import <WXApiObject.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <WeiboSDK.h>



typedef NS_ENUM(NSUInteger, CYSharePlatform) {
    CYSharePlatformNone,
    CYSharePlatformWechat,
    CYSharePlatformQQ,
    CYSharePlatformWeibo
};



@implementation CYShareObject

- (void)dealloc
{
    DLog(@"ShareObject dealloc");
}

@end



@interface CYShareManager ()<WXApiDelegate, QQApiInterfaceDelegate, TencentSessionDelegate, WeiboSDKDelegate>

@property(nonatomic, copy)void (^currentComplete)(BOOL, NSString *);
@property(nonatomic, assign)CYSharePlatform currentPlatform;
@property(nonatomic, strong)TencentOAuth *tencentOAuth;

@end


@implementation CYShareManager

+ (instancetype)standardManager
{
    static CYShareManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[CYShareManager alloc] init];
    });
    return manager;
}

- (instancetype)init
{
    self = [super init];
    if(self)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [WXApi registerApp:WECHAT_APP_ID];
            self.tencentOAuth = [[TencentOAuth alloc] initWithAppId:QQ_APP_ID andDelegate:self];
            [WeiboSDK registerApp:WEIBO_KEY];
        });
    }
    return self;
}

- (void)shareWithObject:(CYShareObject *)object complete:(void (^)(BOOL, NSString *))complete
{
    CYSharedGlobal.outsideSource = CYApplicationOutsiteSourceShare;
    
    self.currentComplete = complete;

    switch(object.type)
    {
        case CYShareTypeURL:
        {
            [self shareURLToTarget:object.target url:object.url thumb:object.thumb thumbURL:object.thumbURL title:object.title detail:object.detail];
            break;
        }
    }
}

- (void)handleOpenURL:(NSURL *)url
{
    switch(self.currentPlatform)
    {
        case CYSharePlatformWechat:
        {
            [WXApi handleOpenURL:url delegate:self];
            break;
        }
        case CYSharePlatformQQ:
        {
            [QQApiInterface handleOpenURL:url delegate:self];
            break;
        }
        case CYSharePlatformWeibo:
        {
            [WeiboSDK handleOpenURL:url delegate:self];
            break;
        }
        case CYSharePlatformNone:
        {
            break;
        }
    }
    self.currentPlatform = CYSharePlatformNone;
}

- (void)completeWithSucceed:(BOOL)succeed message:(NSString *)message
{
    if(self.currentComplete)
    {
        self.currentComplete(succeed, message);
    }
    self.currentComplete = nil;
    if(succeed)
    {
        [SVProgressHUD showSuccessWithStatus:@"分享成功"];
    }
}

#pragma mark - WXApiDelegate & QQApiInterfaceDelegate
- (void)onResp:(id)resp
{
    if([resp isKindOfClass:[BaseResp class]])
    {
        NSString *message = @"分享失败";
        BOOL succeed = NO;
        if([resp errCode] == 0)
        {
            message = @"分享成功";
            succeed = YES;
        }
        [self completeWithSucceed:succeed message:message];
    }
    else if([resp isKindOfClass:[QQBaseResp class]])
    {
        NSString *message = @"分享失败";
        BOOL succeed = NO;
        if([(QQBaseResp *)resp result].integerValue == 0)
        {
            message = @"分享成功";
            succeed = YES;
        }
        [self completeWithSucceed:succeed message:message];
    }
}

- (void)onReq:(id)req
{
    
}

- (void)isOnlineResponse:(NSDictionary *)response
{
    
}

#pragma mark - WeiboSDKDelegate
- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    NSString *message = @"分享失败";
    BOOL succeed = NO;
    if(response.statusCode == WeiboSDKResponseStatusCodeSuccess)
    {
        message = @"分享成功";
        succeed = YES;
    }
    [self completeWithSucceed:succeed message:message];
}

- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{
    
}


#pragma mark - TencentSessionDelegate
- (void)tencentDidLogin
{
    
}

- (void)tencentDidNotLogin:(BOOL)cancelled
{
    
}

- (void)tencentDidNotNetWork
{
    
}

#pragma mark - Private Method
- (void)shareURLToTarget:(CYShareTarget)target url:(NSString *)url thumb:(UIImage *)thumb thumbURL:(NSURL *)thumbURL title:(NSString *)title detail:(NSString *)detail
{
    switch(target)
    {
        case CYShareTargetWechat:
        case CYShareTargetWechatTimeLine:
        {
            self.currentPlatform = CYSharePlatformWechat;
            int scene = target == CYShareTargetWechat ? WXSceneSession : WXSceneTimeline;
            [self shareURLToWechatWithScene:scene url:url thumb:thumb title:title detail:detail];
            break;
        }
        case CYShareTargetQQ:
        {
            self.currentPlatform = CYSharePlatformQQ;
            [self shareURLToQQWithUrl:url thumbURL:thumbURL title:title detail:detail];
            break;
        }
        case CYShareTargetWeibo:
        {
            self.currentPlatform = CYSharePlatformWeibo;
            [self shareURLToWeiboWithUrl:url title:title detail:detail thumb:UIImageJPEGRepresentation(thumb, 0.7)];
            break;
        }
    }
}

- (void)shareURLToWechatWithScene:(int)scene url:(NSString *)url thumb:(UIImage *)thumb title:(NSString *)title detail:(NSString *)detail
{
    WXWebpageObject *webpageObject = [WXWebpageObject object];
    webpageObject.webpageUrl = url;
    
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = title;
    message.description = detail;
    [message setThumbImage:thumb];
    message.mediaObject = webpageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = scene;
    
    BOOL flag = [WXApi sendReq:req];
    if(flag == NO)
    {
        self.currentPlatform = CYSharePlatformNone;
        [self completeWithSucceed:NO message:@"分享失败"];
    }
}

- (void)shareURLToQQWithUrl:(NSString *)url thumbURL:(NSURL *)thumbURL title:(NSString *)title detail:(NSString *)detail
{
    QQApiNewsObject *newsObj = [QQApiNewsObject objectWithURL:url.tc_url title:title description:detail previewImageURL:thumbURL];
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:newsObj];
    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
    if(sent != EQQAPISENDSUCESS && sent != EQQAPIAPPSHAREASYNC)
    {
        self.currentPlatform = CYSharePlatformNone;
        [self completeWithSucceed:NO message:@"分享失败"];
    }
}

- (void)shareURLToWeiboWithUrl:(NSString *)url title:(NSString *)title detail:(NSString *)detail thumb:(NSData *)thumb
{
    WBWebpageObject *webpageObject = [WBWebpageObject object];
    webpageObject.webpageUrl = url;
    webpageObject.objectID = [NSUUID UUID].UUIDString;
    webpageObject.title = title;
    webpageObject.description = detail;
    webpageObject.thumbnailData = thumb;
    webpageObject.scheme = @"https://api.weibo.com/aouth2/default.html";
    
    WBMessageObject *messageObject = [WBMessageObject message];
    messageObject.mediaObject = webpageObject;
    
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:messageObject];
    
    BOOL flag = [WeiboSDK sendRequest:request];
    if(flag == NO)
    {
        self.currentPlatform = CYSharePlatformNone;
        [self completeWithSucceed:NO message:@"分享失败"];
    }
}

@end
